/*
 * The MIT License
 * 
 * Copyright (c) 2008 Comcast Interactive Media
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package cim.sf.core.command.equinox;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import cim.sf.core.command.CommandInvocation;

import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;

import org.eclipse.osgi.framework.console.CommandInterpreter;
import org.eclipse.osgi.framework.console.CommandProvider;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;

/**
 * 
 * @author <a href="mailto:jeremy_volkman@cable.comcast.com">Jeremy Volkman</a>
 *
 */
public class EquinoxCommandRegistrar {

    private ArrayList<EquinoxCommand> commands;
    private BundleContext context = null;
    private List<ServiceRegistration> registeredCommands = null;
    
    public EquinoxCommandRegistrar(CommandProvider obj) {
        Class<?> clazz = obj.getClass();
        
        commands = new ArrayList<EquinoxCommand>();
        String[] helpLines = obj.getHelp() != null ? 
                obj.getHelp().split("\n") : new String[0];
        
        // Step through this class' methods and look for command methods.
        Method[] methods = clazz.getDeclaredMethods();
        for (Method m : methods) {
            // Make sure this method has the proper signature.
            Class<?>[] paramTypes = m.getParameterTypes();
            if (m.getName().charAt(0) != '_' || paramTypes.length != 1 || paramTypes[0] != CommandInterpreter.class) {
                continue;
            }

            String commandName = m.getName().substring(1);
            String description = null;
            for (String helpLine : helpLines) {
                if (helpLine.trim().startsWith(commandName)) {
                    description = helpLine.trim();
                }
            
            }
            EquinoxCommand cmd = new EquinoxCommand(m, obj, commandName, description);
            commands.add(cmd);
        }
        commands.trimToSize();
    }
    
    public void open(BundleContext context) {
        close();
        this.context = context;
        registeredCommands = new ArrayList<ServiceRegistration>(commands.size());
        for (EquinoxCommand c : commands) {
            Dictionary<String, Object> properties = new Hashtable<String, Object>();
            properties.put("command.path", c.getPath());
            registeredCommands.add(context.registerService(cim.sf.core.command.Command.class.getName(), 
                            c, properties));
        }
    }
    
    public void close() {
        if (context != null && registeredCommands != null) {
            for (ServiceRegistration sr : registeredCommands) {
                try {
                    sr.unregister();
                } catch (IllegalStateException e) {
                    // Already unregistered
                }
            }
        }
        context = null;
        registeredCommands = null;
    }
    
    private static class EquinoxCommand implements cim.sf.core.command.Command {

        private Method method;
        private Object obj;
        private String commandName;
        private String description;
        
        private EquinoxCommand(Method method, CommandProvider obj, String commandName, String description) {
            this.method = method;
            this.commandName = commandName;
            this.description = description;
            this.obj = obj;
        }
        
        public int execute(CommandInvocation ci) {
            try {
                CommandInterpreter terp = new CommandInterpreterAdapter(ci);
                method.setAccessible(true);
                method.invoke(obj, terp);
                return 0;
            } catch (InvocationTargetException e) {
                if (e.getCause() instanceof RuntimeException) {
                    throw (RuntimeException) e.getCause();
                } else if (e.getCause() != null) {
                    throw new RuntimeException(e.getCause());
                } else {
                    throw new RuntimeException(e);
                }
            } catch (RuntimeException e) {
                throw e;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        public String getDescription() {
            return description;
        }

        public String getPath() {
            return "/equinox/" + commandName;
        }

        public String[] getUsage() {
            return null;
        }

    }

}
